//
//  SWStatusPictureView.swift
//  MYSwiftWeiBo
//
//  Created by shingwai chan on 16/3/5.
//  Copyright © 2016年 ChanShingWai. All rights reserved.
//

import UIKit
import SDWebImage

//最大列数
private let maxColumn = 3
//每个cell的间距
private let SWStatusPictureViewCellMargin:CGFloat = 10
//一个cell的宽高
private let SWStatusPictureWH = (UIScreen.width - 2 * SWStatusCellMargin - (CGFloat(maxColumn) - 1) * SWStatusPictureViewCellMargin) / CGFloat(maxColumn)
//cellSize
private let SWStatusPictureSize = CGSize(width: SWStatusPictureWH, height: SWStatusPictureWH)

private let SWCellID = "pictureCell"

class SWStatusPictureView: UICollectionView {

    //MARK:属性
    //一个collectionView要对应一个layout
    let layout :UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    var status: SWStatus? {
        didSet {
            //重新计算图片view的大小
            let viewSize = self.viewSize()
            //重新约束
            self.snp_updateConstraints{ (make) -> Void in
                make.size.equalTo(viewSize)
            }
            reloadData()
        }
    }
    
    func viewSize() -> CGSize {
        
        let count = status?.storePictureURLs?.count ?? 0
        //没有图片
        if count == 0{
            return CGSizeZero
        }
        
        if count == 1{
            var size = CGSize(width: 180, height: 120)
            //拿到缓存的图片
            let imageURLString = status?.storePictureURLs?.first?.absoluteString
            
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(imageURLString!){
                //获取到缓存的图片大小
                size = image.size
            }
            //图片宽度太小或太大
            if size.width < 40 {
                size.width = 40
            }else if size.width > UIScreen.width * 0.5 {
                size.width = UIScreen.width * 0.5
            }
            
            layout.itemSize = size
            layout.minimumLineSpacing = 0
            layout.minimumInteritemSpacing = 0
//             print("size: \(size)")
            return size
        }
        
        //一张图片以上
        layout.itemSize = SWStatusPictureSize
        layout.minimumInteritemSpacing  = SWStatusPictureViewCellMargin
        layout.minimumLineSpacing = SWStatusPictureViewCellMargin
        
        //列数
        var column = maxColumn
        if count == 2 || count == 4 { //当2 张或4张
            column = 2
        }
        //行数
        let row  = (count + column - 1) / column
        
        let width = CGFloat(column) * SWStatusPictureWH + (CGFloat(column) - 1) * SWStatusPictureViewCellMargin
        
        let height = CGFloat(row) * SWStatusPictureWH + (CGFloat(row) - 1) * SWStatusPictureViewCellMargin
        
//        print("count: \(count), column: \(column), row: \(row), width: \(width), height: \(height)")
        //整个pictureView的大小
        return CGSize(width: width, height: height)
    }
    
    
    init() {
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        backgroundColor = UIColor.clearColor()
        self.delegate = self
        self.dataSource = self
        //注册cell
        self.registerClass(SWStatusPictureCell.self, forCellWithReuseIdentifier: SWCellID)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
//MARK: -- collectionViewDelegate
extension SWStatusPictureView: UICollectionViewDelegate , UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.storePictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(SWCellID, forIndexPath: indexPath) as! SWStatusPictureCell
        
        cell.imageURL = status?.storePictureURLs![indexPath.item]
        
        return cell
    }


}
//MARK: -- SWStatusPictureCell
class SWStatusPictureCell : UICollectionViewCell {

    var imageURL: NSURL? {
        didSet {
            //设置图片
            bkImageView.sd_setImageWithURL(imageURL)
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(bkImageView)
        //添加约束
        bkImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        //填充模式
        bkImageView.contentMode = UIViewContentMode.ScaleAspectFill
        //裁剪
        bkImageView.clipsToBounds = true
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var bkImageView = UIImageView(image: nil)
}

